<script setup>
/* eslint-disable vue/multi-word-component-names */
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, ArrowDown, Promotion, ChatDotSquare, Connection } from '@element-plus/icons-vue'
import request from '@/utils/request'


// 路由实例
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const isLoggedIn = ref(false)
const username = ref('当前用户')
const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
const userId = ref(null)
const categories = ref([])
const loginDialogVisible = ref(false)
const registerDialogVisible = ref(false)
const loginForm = ref({
  username: '',
  password: '',
  remember: false
})
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})
// 加载状态
const loginLoading = ref(false)
const registerLoading = ref(false)

// 生命周期钩子
onMounted(() => {
  // 检查用户登录状态
  checkLoginStatus()
  // 获取分类列表
  fetchCategories()
})

// 方法
// 检查登录状态
const checkLoginStatus = async () => {
  // 从本地存储获取token
  const token = localStorage.getItem('token')
  if (!token) {
    isLoggedIn.value = false
    return
  }

  try {
    // 验证token并获取用户信息
    const res = await request.get('/user/info', {
      headers: {
        Authorization: token
      }
    })
    
    if (res.data.code === '200') {
      isLoggedIn.value = true
      const userInfo = res.data.data
      username.value = userInfo.username || '用户'
      userAvatar.value = userInfo.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      userId.value = userInfo.id
    } else {
      // token无效，清除本地存储
      localStorage.removeItem('token')
      isLoggedIn.value = false
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    localStorage.removeItem('token')
    isLoggedIn.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/category/list')
    
    if (res.data.code === '200') {
      categories.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)
      // 加载默认分类数据
      loadDefaultCategories()
    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
    // 加载默认分类数据
    loadDefaultCategories()
  }
}

// 加载默认分类数据
const loadDefaultCategories = () => {
  categories.value = [
    { id: 1, name: '科技' },
    { id: 2, name: '娱乐' },
    { id: 3, name: '体育' },
    { id: 4, name: '国际' },
    { id: 5, name: '财经' },
    { id: 6, name: '教育' },
    { id: 7, name: '文化' },
    { id: 8, name: '动漫' }
  ]
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { q: searchKeyword.value }
    })
    searchKeyword.value = ''
  }
}

const handleCategoryClick = (categoryId) => {
  router.push(`/category/${categoryId}`)
}

const handleLogin = () => {
  loginDialogVisible.value = true
}

const handleRegister = () => {
  registerDialogVisible.value = true
}

const handlePublish = () => {
  router.push('/publish')
}

const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push(`/user/${userId.value}`)
      break
    case 'settings':
      router.push('/settings')
      break
    case 'messages':
      router.push('/messages')
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogout = async () => {
  try {
    const token = localStorage.getItem('token')
    if (token) {
      // 调用登出接口
      await request.post('/user/logout', null, {
        headers: {
          Authorization: token
        }
      })
    }
  } catch (error) {
    console.error('登出失败:', error)
  } finally {
    // 无论请求成功与否，都清除本地存储并更新状态
    localStorage.removeItem('token')
    isLoggedIn.value = false
    ElMessage.success('已退出登录')
    
    // 如果当前页面需要登录权限，则跳转到首页
    if (router.currentRoute.value.path.includes('/user/') || 
        router.currentRoute.value.path === '/publish' ||
        router.currentRoute.value.path === '/settings' ||
        router.currentRoute.value.path === '/messages') {
      router.push('/')
    }
  }
}

const switchToRegister = () => {
  loginDialogVisible.value = false
  registerDialogVisible.value = true
}

const switchToLogin = () => {
  registerDialogVisible.value = false
  loginDialogVisible.value = true
}

const submitLogin = async () => {
  // 表单验证
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  
  loginLoading.value = true
  try {
    // 调用登录接口
    const res = await request.post('/user/login', {
      username: loginForm.value.username,
      password: loginForm.value.password
    })
    
    if (res.data.code === '200') {
      // 登录成功，保存token
      const token = res.data.data.token
      localStorage.setItem('token', token)
      if (loginForm.value.remember) {
        // 如果选择了记住我，可以设置token有效期更长
        localStorage.setItem('rememberMe', 'true')
      }
      
      // 更新登录状态
      isLoggedIn.value = true
      // 获取用户信息
      await checkLoginStatus()
      
      // 关闭登录框
      loginDialogVisible.value = false
      // 清空表单
      loginForm.value = {
        username: '',
        password: '',
        remember: false
      }
      
      ElMessage.success('登录成功')
    } else {
      ElMessage.error(res.data.msg || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录请求失败:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loginLoading.value = false
  }
}

const submitRegister = async () => {
  // 表单验证
  if (!registerForm.value.username || !registerForm.value.email || !registerForm.value.password) {
    ElMessage.warning('请填写完整的注册信息')
    return
  }
  
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  registerLoading.value = true
  try {
    // 调用注册接口
    const res = await request.post('/user/register', {
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password
    })
    
    if (res.data.code === '200') {
      // 注册成功
      registerDialogVisible.value = false
      // 清空表单
      registerForm.value = {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
      
      ElMessage.success('注册成功，请登录')
      // 打开登录框
      loginDialogVisible.value = true
    } else {
      ElMessage.error(res.data.msg || '注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('注册请求失败:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    registerLoading.value = false
  }
}
</script> 